<?php

namespace App\Http\Controllers\Admin;

use App\Models\Agent;
use App\Models\Dictionary;
use App\Models\Order;
use App\Models\OrderRecord;
use App\Models\Product;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $name=$request->input('name','');
        $category_id_first=$request->input('category_id_first','');
        $category_id_second=$request->input('category_id_second','');
        $agent_id=$request->input('agent_id','');
        $loan_start=$request->input('loan_start','');
        $loan_end=$request->input('loan_end','');
        $age_start=$request->input('age_start','');
        $age_end=$request->input('age_end','');
        $repay_start=$request->input('repay_start','');
        $repay_end=$request->input('repay_end','');
        $repay_type=$request->input('repay_type','');
        $status=$request->input('status','');

        $query=Product::select();
        if($name!=''){
            $query->where('name','like',"%$name%");
        }
        if($category_id_first!=''){
            $query->where('basic_info->category_id_first',$category_id_first);
        }
        if($category_id_second!=''){
            $query->where('basic_info->category_id_second',$category_id_second);
        }
        if($agent_id!=''){
            $query->where('basic_info->agent_id',$agent_id);
        }
        /*放款额度start*/
        if($loan_start && !$loan_end){
            $loan_start=floatval($loan_start);
            $query->where(function ($query) use ($loan_start){
                $query->where(DB::raw('basic_info->>"$.loan_start"'),'>=',$loan_start)->orWhere(function ($query) use ($loan_start){
                    $query->where(DB::raw('basic_info->>"$.loan_start"'),'<',$loan_start)
                        ->where(DB::raw('basic_info->>"$.loan_end"'),'>=',$loan_start);
                });
            });
        }
        if(!$loan_start && $loan_end){
            $loan_end=floatval($loan_end);
            $query->where(function ($query) use ($loan_end){
                $query->where(DB::raw('basic_info->>"$.loan_end"'),'<=',$loan_end)->orWhere(function ($query) use ($loan_end){
                   $query->where(DB::raw('basic_info->>"$.loan_start"'),'<=',$loan_end)
                       ->where(DB::raw('basic_info->>"$.loan_end"'),'>=',$loan_end);
                });
            });
        }
        if($loan_start && $loan_end){
            $loan_start=floatval($loan_start);
            $loan_end=floatval($loan_end);
            if($loan_start>$loan_end){
                die('<script>alert("放款额度前值不能比后值大");history.back();</script>');
            }
            $query->where(function ($query) use ($loan_start,$loan_end){
                $query->where(DB::raw('basic_info->>"$.loan_start"'),'<=',$loan_start)
                    ->where(DB::raw('basic_info->>"$.loan_end"'),'>=',$loan_start)
                    ->orWhere(function ($query) use ($loan_start,$loan_end){
                        $query->where(DB::raw('basic_info->>"$.loan_end"'),'>=',$loan_start)
                            ->where(DB::raw('basic_info->>"$.loan_end"'),'<=',$loan_end);
                    })->orWhere(function ($query) use ($loan_start,$loan_end){
                        $query->where(DB::raw('basic_info->>"$.loan_start"'),'<=',$loan_end)
                            ->where(DB::raw('basic_info->>"$.loan_end"'),'>=',$loan_end);
                    });
            });
        }
        /*放款额度end*/

        /*年龄start*/
        if($age_start && !$age_end){
            $age_start=floatval($age_start);
            $query->where(function ($query) use ($age_start){
                $query->where(DB::raw('basic_info->>"$.age_start"'),'>=',$age_start)->orWhere(function ($query) use ($age_start){
                    $query->where(DB::raw('basic_info->>"$.age_start"'),'<',$age_start)
                        ->where(DB::raw('basic_info->>"$.age_end"'),'>=',$age_start);
                });
            });
        }
        if(!$age_start && $age_end){
            $age_end=floatval($age_end);
            $query->where(function ($query) use ($age_end){
                $query->where(DB::raw('basic_info->>"$.age_end"'),'<=',$age_end)->orWhere(function ($query) use ($age_end){
                    $query->where(DB::raw('basic_info->>"$.age_start"'),'<=',$age_end)
                        ->where(DB::raw('basic_info->>"$.age_end"'),'>=',$age_end);
                });
            });
        }
        if($age_start && $age_end){
            $age_start=floatval($age_start);
            $age_end=floatval($age_start);
            if($age_start>$age_end){
                die('<script>alert("年龄要求前值不能比后值大");history.back();</script>');
            }
            $query->where(function ($query) use ($age_start,$age_end){
                $query->where(DB::raw('basic_info->>"$.age_start"'),'<=',$age_start)
                    ->where(DB::raw('basic_info->>"$.age_end"'),'>=',$age_start)
                    ->orWhere(function ($query) use ($age_start,$age_end){
                        $query->where(DB::raw('basic_info->>"$.age_start"'),'>=',$age_start)
                            ->where(DB::raw('basic_info->>"$.age_end"'),'<=',$age_end);
                    })->orWhere(function ($query) use ($age_start,$age_end){
                        $query->where(DB::raw('basic_info->>"$.age_start"'),'<=',$age_end)
                            ->where(DB::raw('basic_info->>"$.age_end"'),'>=',$age_end);
                    });
            });
        }
        /*年龄end*/

        /*还款期限start*/
        if($repay_start && !$repay_end){
            $repay_start=floatval($repay_start);
            $query->where(function ($query) use ($repay_start){
                $query->where(DB::raw('basic_info->>"$.repay_start"'),'>=',$repay_start)->orWhere(function ($query) use ($repay_start){
                    $query->where(DB::raw('basic_info->>"$.repay_start"'),'<',$repay_start)
                        ->where(DB::raw('basic_info->>"$.repay_end"'),'>=',$repay_start);
                });
            });
        }
        if(!$repay_start && $repay_end){
            $repay_end=floatval($repay_end);
            $query->where(function ($query) use ($repay_end){
                $query->where(DB::raw('basic_info->>"$.repay_end"'),'<=',$repay_end)->orWhere(function ($query) use ($repay_end){
                    $query->where(DB::raw('basic_info->>"$.repay_start"'),'<=',$repay_end)
                        ->where(DB::raw('basic_info->>"$.repay_end"'),'>=',$repay_end);
                });
            });
        }
        if($repay_start && $repay_end){
            $repay_start=floatval($repay_start);
            $repay_end=floatval($repay_end);
            if($repay_start>$repay_end){
                die('<script>alert("还款期限前值不能比后值大");history.back();</script>');
            }
            $query->where(function ($query) use ($repay_start,$repay_end){
                $query->where(DB::raw('basic_info->>"$.repay_start"'),'<=',$repay_start)
                    ->where(DB::raw('basic_info->>"$.repay_end"'),'>=',$repay_start)
                    ->orWhere(function ($query) use ($repay_start,$repay_end){
                        $query->where(DB::raw('basic_info->>"$.repay_start"'),'>=',$repay_start)
                            ->where(DB::raw('basic_info->>"$.repay_end"'),'<=',$repay_end);
                    })->orWhere(function ($query) use ($repay_start,$repay_end){
                        $query->where(DB::raw('basic_info->>"$.repay_start"'),'<=',$repay_end)
                            ->where(DB::raw('basic_info->>"$.repay_end"'),'>=',$repay_end);
                    });
            });
        }

        /*还款期限end*/

        if($repay_type!=''){
            $query->where('basic_info->repay_type',$repay_type);
        }
        if($status!=''){
            $query->where('status',$status);
        }
        $products=$query->orderBy('id','desc')->paginate();
        $products->appends([
            'name'=>$name,
            'category_id_first'=>$category_id_first,
            'category_id_second'=>$category_id_second,
            'agent_id'=>$agent_id,
            'loan_start'=>$loan_start,
            'loan_end'=>$loan_end,
            'age_start'=>$age_start,
            'age_end'=>$age_end,
            'repay_start'=>$repay_start,
            'repay_end'=>$repay_end,
            'repay_type'=>$repay_type,
            'status'=>$status
        ]);
        $products->name=$name;
        $products->category_id_first=$category_id_first;
        $products->category_id_second=$category_id_second;
        $products->agent_id=$agent_id;
        $products->loan_start=$loan_start;
        $products->loan_end=$loan_end;
        $products->age_start=$age_start;
        $products->age_end=$age_end;
        $products->repay_start=$repay_start;
        $products->repay_end=$repay_end;
        $products->repay_type=$repay_type;
        $products->status=$status;

        return view('Admin.Product.index',compact('products'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {

        return view('Admin.Product.create');

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $this->validate($request,[
            'name'=>'required|unique:products',
            'basic_info'=>'required',
            'apply_condition'=>'required',
            'apply_material'=>'required',
            'status'=>'required'
        ],[
            'name.required'=>'请填写产品名称',
            'name.unique'=>'该产品已存在',
            'basic_info.required'=>'请完善基本信息',
            'apply_condition.required'=>'请填写申请条件',
            'apply_material.required'=>'请填写申请材料',
            'status.required'=>'请选择产品状态'
        ]);
        $data=$request->all();
        $data['is_hot']=isset($data['is_hot'])?$data['is_hot']:'0';
        $hotNum=Product::where('basic_info->category_id_first',$data['basic_info']['category_id_first'])->where('is_hot',1)->count();
        if($data['is_hot']==1 && $hotNum>=3){
            return response()->json(['status'=>201,'msg'=>'同一分类下最多标记3个产品为热门产品']);
        }
        if(Product::create($data)){
            return response()->json(['status'=>200,'msg'=>'添加成功']);
        }else{
            return response()->json(['status'=>202,'msg'=>'添加失败']);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {

        $product=Product::findOrFail($id);
        $category_first=Dictionary::find($product->basic_info['category_id_first']);
        if($category_first){
            $product->category_name_first=$category_first->name;
        }
        $category_second=Dictionary::find($product->basic_info['category_id_second']);
        if($category_second){
            $product->category_name_second=$category_second->name;
        }
        $agent=Agent::find($product->basic_info['agent_id']);
        if($agent){
            $product->agent_name=$agent->name;
        }
        $repay=Dictionary::find($product->basic_info['repay_type']);
        if($repay){
            $product->repay_type=$repay->name;
        }
        $require_white='';
        switch ($product->basic_info['require_white']){
            case '0':$require_white='无要求';break;
            case '1':$require_white='不做白户';break;
            default;
        }
        $product->require_white=$require_white;
        $require_workplace='';
        switch ($product->basic_info['require_workplace']){
            case '0':$require_workplace='无要求';break;
            case '1':$require_workplace='要求在申请地工作';break;
            default;
        }
        $product->require_workplace=$require_workplace;
        $require_house='';
        switch ($product->basic_info['require_house']){
            case '0':$require_house='无要求';break;
            case '1':$require_house='要求申请地房产';break;
            case '2':$require_house='有房产即可';break;
            default;
        }
        $product->require_house=$require_house;
        $require_live='';
        switch ($product->basic_info['require_live']){
            case '0':$require_live='无要求';break;
            case '1':$require_live='要求在申请地居住';break;
            default;
        }
        $product->require_live=$require_live;
        return view('Admin.Product.show',compact('product'));

    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {

        $product=Product::findOrFail($id);

        return view('Admin.Product.edit',compact('product'));

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request,[
            'name'=>'required|unique:products,name,'.$id,
            'basic_info'=>'required',
            'apply_condition'=>'required',
            'apply_material'=>'required',
            'status'=>'required'
        ],[
            'name.required'=>'请填写产品名称',
            'name.unique'=>'该产品已存在',
            'basic_info.required'=>'请完善基本信息',
            'apply_condition.required'=>'请填写申请条件',
            'apply_material.required'=>'请填写申请材料',
            'status.required'=>'请选择产品状态'
        ]);
        $data=$request->all();
        $data['is_hot']=isset($data['is_hot'])?$data['is_hot']:0;
        $hotNum=Product::where('basic_info->category_id_first',$data['basic_info']['category_id_first'])->where('is_hot',1)->where('id','!=',$id)->count();
        if($data['is_hot']==1 && $hotNum>=3){
            return response()->json(['status'=>201,'msg'=>'同一分类下最多标记3个产品为热门产品']);
        }
        if(Product::updateOrCreate(['id'=>$id],$data)){
            return response()->json(['status'=>200,'msg'=>'修改成功']);
        }else{
            return response()->json(['status'=>201,'msg'=>'修改失败']);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $product=Product::find($id);
        if($product==null){
            return response()->json(['status'=>201,'msg'=>'该产品已被删除,请勿重复操作']);
        }
        /*$order=Order::where(['status'=>0])->where(DB::raw('confirm_loan->>"$.product_id"'),'=',$id)->first();
        if($order){
            return response()->json(['status'=>203,'msg'=>'用户申请中,无法删除']);
        }*/
        if($product->delete()){
            return response()->json(['status'=>200,'msg'=>'删除成功']);
        }else{
            return response()->json(['status'=>202,'msg'=>'删除失败']);
        }
    }

    /*
     * 添加标签
     * */
    public function add_label(Request $request){

        return view('Admin.Product.add_label');
    }

    /*
     * 获取二级分类
     * */
    public function getSecondCategory(Request $request){

        $id=$request->input('id');
        $categories=Dictionary::select('id','name')->where(['pid'=>$id])->get();
        return $categories;
    }

    /*
     * 上下架产品
     * */
    public function status(Request $request){
        $id=$request->id;
        $status=$request->status;
        $product=Product::find($id);
        if($product==null){
            return response()->json(['status'=>201,'msg'=>'该产品已被删除']);
        }
        if($status==1){
            $product->status=0;
            $msg='下架';
        }else{
            $product->status=1;
            $msg='上架';
        }
        if($product->save()){
            return response()->json(['status'=>200,'msg'=>$msg.'成功']);
        }else{
            return response()->json(['status'=>202,'msg'=>$msg.'失败']);
        }
    }

    /**
     * 根据分类获取产品
     */
    public function getCategoryProduct(Request $request){
        if($request->id!==''){
            if($request->type == 1){//一级
                if($request->id == 0){
                    $res = Product::all(['name','id']);
                }else {
                    $res = Product::where(['basic_info->category_id_first' => $request->id])->get(['name', 'id']);
                }
            }else{//二级
                if($request->id == 0){
                    if($request->pid > 0){
                        $res = Product::where(['basic_info->category_id_first' => $request->pid])->get(['name', 'id']);
                    }else{
                        $res = Product::all(['name','id']);
                    }
                }else {
                    $res = Product::where(['basic_info->category_id_second' => $request->id])->get(['name', 'id']);
                }
            }
            $this->set('data',$res);
        }else{
            $this->set('code',1);
            $this->set('message','暂无数据');
        }
        return $this->ajaxResponse();
    }

}
